import os
from openai import OpenAI
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from core.models.student import Student
from core.models.classinfo import ClassInfo
from core.models.semester import Semester
from core.models.student_comment import StudentComment
from django.utils import timezone
@csrf_exempt
def generate_student_comment(request):
    if request.method == 'POST':
        student_id = request.POST.get('student_id')
        class_id = request.POST.get('class_id')
        semester_id = request.POST.get('semester_id')
        
        try:
            # 获取学生、班级和学期信息
            student = Student.objects.get(id=student_id)
            class_info = ClassInfo.objects.get(id=class_id)
            semester = Semester.objects.get(id=semester_id)
            
            # 准备提示文本
            prompt = f"请为{student.name}同学生成{semester}的评语，该同学在{class_info.name}班。"
            
            # 调用豆包API
            client = OpenAI(
                base_url="https://ark.cn-beijing.volces.com/api/v3",
                api_key=os.environ.get("ARK_API_KEY"),
            )
            
            response = client.chat.completions.create(
                model="doubao-seed-1-6-250615",
                messages=[
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": prompt},
                        ],
                    }
                ],
            )
            
            comment_content = response.choices[0].message.content
            
            # 保存或更新评语
            comment, created = StudentComment.objects.get_or_create(
                student=student,
                class_info=class_info,
                semester=semester,
                defaults={'content': comment_content, 'is_generated': True}
            )
            
            if not created:
                comment.content = comment_content
                comment.is_generated = True
                comment.save()
            
            return JsonResponse({
                'success': True,
                'comment_id': comment.id,
                'content': comment_content
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            }, status=500)
    else:
        return JsonResponse({'success': False, 'error': '只支持POST请求'}, status=405)

def get_doubao_answer(request):
    # 请确保您已将 API Key 存储在环境变量 ARK_API_KEY 中
    # 初始化Ark客户端，从环境变量中读取您的API Key
    try:
        client = OpenAI(
            # 此为默认路径，您可根据业务所在地域进行配置
            base_url="https://ark.cn-beijing.volces.com/api/v3",
            # 从环境变量中获取您的 API Key。此为默认方式，您可根据需要进行修改
            api_key=os.environ.get("ARK_API_KEY"),
        
        )

        response = client.chat.completions.create(
            # 指定您创建的方舟推理接入点 ID，此处已帮您修改为您的推理接入点 ID
            model="doubao-seed-1-6-250615",
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": "https://ark-project.tos-cn-beijing.ivolces.com/images/view.jpeg"
                            },
                        },
                        {"type": "text", "text": "这是哪里？"},
                    ],
                }
            ],
        )
        print(response.choices[0].message.content)
        # return JsonResponse({"answer": response.choices[0].message.content})
        return HttpResponse(response.choices[0].message.content)
    except Exception as e:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(f"API调用失败: {str(e)}", exc_info=True)
        return JsonResponse({
            "success": False,
            "error": str(e),
            "error_type": type(e).__name__
        }, status=500)
